package com.yinhd.study.dockingPlatform.register;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * @program: study
 * @description:
 * @Author: chengl
 * @create: 2022-05-06 11:26
 **/
public class KeepAlive {

    @Autowired
    Register register;

    int count = 0;

    @Scheduled(cron = "")
    public void keepalive() throws InterruptedException {
        try {

            boolean post = restConnect("", "POST", "", "");
            if (post){
                return ;
            }else {
                TimeUnit.SECONDS.sleep(90);
                keepalive();
            }
        }catch (Exception e){
              TimeUnit.SECONDS.sleep(90);
              keepalive();
        }finally {
            if (count>3){
                return;
            }
        }
    }

    public static boolean restConnect(String url,String method,String param,String authentication) {
        String strResult="";
        try {
            URL restUrl=new URL(url);
            HttpURLConnection conn = (HttpURLConnection) restUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod(method);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type","application/viid+json");
            conn.setRequestProperty("User-Identify",authentication);
            conn.setRequestProperty("Connection","keepalive");
            conn.setConnectTimeout(10000);//连接超时 单位毫秒
            conn.setReadTimeout(5000);//读取超时 单位毫秒
            //传递参数
            if (param != null && !"".equals(param)) {
                byte[] bypes = param.getBytes("utf-8");
                conn.getOutputStream().write(bypes);
            }
            conn.connect();
            System.out.println("响应码："+conn.getResponseCode());
            if(conn.getResponseCode() == 200 ){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }
}
